using GameStoreMinimalApi.WebApi.Authorization;
using GameStoreMinimalApi.WebApi.Cors;
using GameStoreMinimalApi.WebApi.Data;
using GameStoreMinimalApi.WebApi.Endpoints;
using GameStoreMinimalApi.WebApi.ErrorHandling;
using GameStoreMinimalApi.WebApi.Middleware;
using GameStoreMinimalApi.WebApi.OpenApi;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace GameStoreMinimalApi.WebApi;

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.Services.AddRepositories(builder.Configuration);

        builder.Services.AddAuthentication().AddJwtBearer();
        builder.Services.AddGameStoreAuthorization();
        builder.Services.AddApiVersioning(options =>
        {
            options.DefaultApiVersion = new(1.0);
            options.AssumeDefaultVersionWhenUnspecified = true;
        })
        .AddApiExplorer(options => options.GroupNameFormat = "'v'VVV");

        builder.Logging.AddJsonConsole(options =>
        {
            options.JsonWriterOptions = new()
            {
                Indented = true,
            };
        });

        builder.Services.AddGameStoreCors(builder.Configuration);

        builder.Services.AddSwaggerGen()
                        .AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>()
                        .AddEndpointsApiExplorer();

        builder.Services.AddHttpLogging(o => { });

        var app = builder.Build();

        app.UseExceptionHandler(exceptionHandlerApp => exceptionHandlerApp.ConfigureExceptionHandler());

        app.UseMiddleware<RequestTimingMiddleware>();

        await app.Services.InitializeDbAsync();

        app.UseHttpLogging();
        app.UseHttpsRedirection();
        app.MapGamesEndpoints();
        app.UseCors();

        app.userGameStoreSwagger();

        app.Run();
    }
}
